<template>
    <view class="w-screen h-screen bg-neutral-1">
        <!-- 文章内容区域 -->
        <scroll-view class="w-screen h-screen" scroll-y>
            <view class="p-4 text-5 leading-10 tracking-wider">
                <view
                    v-if="params.page > 0"
                    class="py-2 text-8 max-w-50% overflow-ellipsis overflow-hidden whitespace-nowrap"
                    >第{{ params.page }}章</view
                >
                <view v-else class="py-2 text-8 max-w-50% overflow-ellipsis overflow-hidden whitespace-nowrap">
                    前言
                </view>
                <view class="whitespace-pre-wrap" style="word-wrap: anywhere">
                    {{ article.content }}
                </view>
                <!-- 底部控制按钮 -->
                <view class="w-full flex justify-between items-center p-3 mt-4">
                    <view
                        @click="prevPage"
                        class="w-22 bg-white text-sm rounded-full flex-center py-1 shadow b-solid b-neutral-1 b-1 b-opacity-50"
                        :class="params.page == 0 ? 'text-gray' : ''"
                        >上一章</view
                    >
                    <view
                        @click="openCatalogue"
                        class="w-22 bg-white text-sm rounded-full flex-center py-1 shadow b-solid b-neutral-1 b-1 b-opacity-50"
                        >目录</view
                    >
                    <view
                        @click="nextPage"
                        class="w-22 bg-white text-sm rounded-full flex-center py-1 shadow b-solid b-neutral-1 b-1 b-opacity-50"
                        :class="params.page == article.totalPageSize ? 'text-gray' : ''"
                        >下一章</view
                    >
                </view>
            </view>
        </scroll-view>

        <!-- 左侧目录 - 点击后显示的章节目录面板 -->
        <view
            v-if="showCatalogue"
            @click="showCatalogue = false"
            class="fixed left-1 w-screen z-50 bg-black bg-opacity-40 catalogue-mask"
            :style="{
                height: showController ? 'calc(100vh - 224px)' : '100vh', // 根据是否显示控制栏调整高度
                top: showController ? '128px' : '0', // 根据是否显示控制栏调整位置
            }"
        >
            <!-- 章节列表滚动区域 -->
            <scroll-view
                scroll-y
                class="chapter-list bg-white flex-col h-full max-w-65% rounded-r-lg shadow-xl"
                :scroll-top="scrollTop"
            >
                <!-- 顶部留白,提升视觉体验 -->
                <view class="py-16"></view>

                <!-- 前言/封面章节 -->
                <view
                    @click="handleChapterClick(0)"
                    class="chapter-item overflow-hidden hover:bg-gray-50 transition-colors duration-200"
                    :class="{ active: 0 == params.page }"
                >
                    <text class="text-ellipsis whitespace-nowrap overflow-hidden font-medium">{{
                        article.articleName
                    }}</text>
                </view>

                <!-- 章节列表循环 -->
                <view
                    v-for="page of pages"
                    :key="page"
                    class="chapter-item overflow-hidden hover:bg-gray-50 transition-colors duration-200"
                    :class="{ active: page == params.page }"
                    @click="handleChapterClick(page)"
                >
                    <text class="text-ellipsis whitespace-nowrap overflow-hidden">第{{ page }}章</text>
                </view>

                <!-- 底部留白 -->
                <view class="py-16"></view>
            </scroll-view>
        </view>

        <!-- 顶部导航栏 -->
        <!-- 这是一个被注释掉的顶部导航栏组件,主要功能包括:
        1. 只有当showController为true时才显示
        2. 固定在页面顶部(fixed定位),宽度100%,白色背景,z-index为10确保显示在上层
        3. 左侧有一个home图标按钮,点击后通过router.replaceAll跳转到书籍列表页
        4. 中间显示当前文章标题(最大宽度40%,超出部分省略)和当前阅读的章节数
        5. 整体高度为5rem
        目前这段代码被注释掉了,说明暂时不需要显示这个导航栏 -->
        <!-- <view v-if="showController" class="fixed left-0 top-0 w-screen bg-white z-10" style="height: 5rem">
            <view class="absolute h-full left-4 top-0 mt-6">
                <view @click="router.replaceAll('/pages/books')" class="ic-round-home text-3xl"></view>
            </view>

            <view class="flex-center flex-col mt-6">
                <view class="w-40% overflow-ellipsis overflow-hidden whitespace-nowrap text-lg">{{
                    article.articleName
                }}</view>
                <view class="mt-1 text-sm text-neutral">第{{ params.page }}章</view>
            </view>
        </view> -->
    </view>
</template>

<script setup lang="ts">
    import { Article, ArticleContent, getArticleContent } from "@/api/api"
    import { useRoute, useRouter } from "uni-mini-router"
    import { computed, ref, watch, nextTick } from "vue"
    import { useReadHistoryStore } from "@/state/readHistory"
    const router = useRouter()
    const route = useRoute()
    const readHistoryStore = useReadHistoryStore()

    const params = computed(() => {
        return {
            id: route.query?.id,
            page: route.query?.page,
        }
    })

    const article = ref({} as Article & ArticleContent)

    const pages = computed(() => {
        const list = [] as number[]
        if (article.value) {
            for (let i = 1; i <= article.value.totalPageSize; i++) {
                list.push(i)
            }
        }
        return list
    })

    const loading = ref(false)
    const showCatalogue = ref(false)
    const showController = ref(false)

    // loadArticle(params.value.id, params.value.page)

    function loadArticle(id: string, page: any) {
        if (id === undefined || page === undefined || page == "") {
            return
        }
        readHistoryStore.setReadPage(id, page)
        loading.value = true
        getArticleContent(id, page).then((r) => {
            article.value = r
            loading.value = false
            uni.setNavigationBarTitle({
                title: r.articleName,
            })
        })
    }

    watch(
        () => params.value,
        (newVal) => {
            loadArticle(newVal.id, newVal.page)
        }
    )

    function prevPage() {
        if (params.value.id === undefined || params.value.page === undefined) {
            return
        }
        if (params.value.page < 1) {
            return
        }
        router.replace(`/pages/read?id=${params.value.id}&page=${parseInt(params.value.page) - 1}`)
    }

    function nextPage() {
        if (params.value.id === undefined || params.value.page === undefined) {
            return
        }
        if (params.value.page == article.value.totalPageSize) {
            return
        }
        router.replace(`/pages/read?id=${params.value.id}&page=${parseInt(params.value.page) + 1}`)
    }

    // 添加 scrollTop ref
    const scrollTop = ref(0)

    // 统一处理打开目录的方法
    const openCatalogue = () => {
        showCatalogue.value = true
        // 确保在DOM更新后再滚动
        nextTick(() => {
            // 延迟一帧执行动，确保scroll-view已经渲染完成
            setTimeout(() => {
                if (params.value.page !== undefined) {
                    scrollToChapter(parseInt(params.value.page))
                }
            }, 50)
        })
    }

    const scrollToChapter = (currentChapterIndex: number) => {
        const itemHeight = 50 // 每个章节项高度
        const paddingHeight = 80 // 顶部和底部各80px的空白区域
        const totalHeight = uni.getSystemInfoSync().windowHeight
        // 计算实际可用容器高度 (rem转px: 1rem = 16px)
        const containerHeight = showController.value
            ? totalHeight - 8 * 16 - 6 * 16 // 减去顶部8rem(128px)和底部6rem(96px)
            : totalHeight

        // 计算目标位置：让当前章节位于屏幕正中间，考虑顶部padding
        let newScrollTop = currentChapterIndex * itemHeight + paddingHeight - containerHeight / 2 + itemHeight / 2

        // 边界处理：确保不会出现负数滚动位置
        newScrollTop = Math.max(0, newScrollTop)

        // 边界处理：确保不会超出最大滚动范围
        // 修正：考虑标题项、所有章节的总���度和上下padding
        const totalContentHeight = (pages.value.length + 1) * itemHeight + paddingHeight * 2
        const maxScrollTop = Math.max(0, totalContentHeight - containerHeight)

        // 如果是最后几章，接滚动到底部
        if (currentChapterIndex >= pages.value.length - 3) {
            newScrollTop = maxScrollTop
        } else {
            newScrollTop = Math.min(newScrollTop, maxScrollTop)
        }

        // 设置滚动位置
        scrollTop.value = newScrollTop
    }

    const handleChapterClick = (page: number) => {
        router.replace(`/pages/read?id=${params.value.id}&page=${page}`)
        showCatalogue.value = false
    }

    // 监听页面变化，自动滚动到对应章节
    watch(
        () => params.value.page,
        (newPage) => {
            if (newPage !== undefined) {
                scrollToChapter(parseInt(newPage))
            }
        }
    )
</script>

<style>
    .catalogue-mask {
        /* 添加遮罩层样式 */
        backdrop-filter: blur(2px);
    }

    .chapter-list {
        /* 修改目录列表样式 */
        background-color: #fff;
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    }

    .chapter-item {
        padding: 15px;
        border-bottom: 1px solid #eee;
        height: 50px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        /* 添加内边距防止文字贴边 */
        padding-right: 20px;
        padding-left: 20px;
    }

    .chapter-item text {
        /* 确保文字完整显示 */
        width: 100%;
        display: block;
    }

    .chapter-item.active {
        color: #45b05d;
        background-color: #f5f5f5;
    }

    /* 添加滚动条样式 */
    ::-webkit-scrollbar {
        width: 4px;
    }

    ::-webkit-scrollbar-thumb {
        background-color: #ddd;
        border-radius: 2px;
    }

    ::-webkit-scrollbar-track {
        background-color: transparent;
    }
</style>
